﻿
; (function ($, window, document, undefined) {

    var pluginName = "grid", defaults = { id: '', key: '', title: {}, cols: [], toolbar: {}, rowindex: true, data: [], pageindex: 0, pagesize: 10, pager: null, rowbind: null };

    function Plugin(element, options) {
        this.element = $(element);
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {

            var $this = this.element,
                $toggle = this.settings.toggle,
                obj = this;

            if (this.isIE() <= 9) {
                return false;
            }

            if (this.settings.id == '') {
                return false;
            }

            this.bind();
        },

        bind: function () {
            var thisobj = this;
            var args = this.settings;
            var editable = args.editable, editpanelid = 'editpanel-' + args.id, editcols = [], editkeys = [], hide = ' style="display:none"';
            args.editpanelid = editpanelid;

            var rowindex = args.rowindex, pager = args.pager, rowbind = args.rowbind, cols = args.cols, data = args.data, isimg = false;
            var thead = rowindex ? '<th style="width:30px;">#</th>' : '';
            $(cols).each(function (i, col) {
                var thwidth = (col.width) ? ' style="width:' + col.width + 'px;"' : '';
                thead += '<th' + thwidth + '>' + col.label + '</th>';
                if (col.edittype && editkeys.indexOf(col.key) < 0) {
                    editkeys.push(col.key);
                    editcols.push(col);
                }
                if (editable && !isimg && col.edittype == 'img') {
                    isimg = true;
                }
            });
            if (editable) {
                thead += '<th></th>';
            }
            var tbody = '';
            $(data).each(function (i, m) {
                tbody += '<tr>';
                tbody += rowindex ? '<td>' + (i + 1) + '</td>' : '';

                if (rowbind) {
                    rowbind(i, m, args);
                }

                $(cols).each(function (j, col) {
                    switch (col.type) {
                        case 'image':
                            var imgtag = '<img src="' + args.imgroot + m[col.key] + '" alt="" style="width:' + args.imgSize[col.key][0] + 'px;height:' + args.imgSize[col.key][1] + 'px;"/>';
                            //console.log(imgtag);
                            if (col.edittype && col.edittype == 'img') {
                                var editclass = ' class="img-' + col.key + '"';
                                tbody += '<td><div' + editclass + '>' + imgtag + '</div><div' + hide + '>' + m[col.key] + '</div><div' + hide + '>' + m[args.key] + '</div></td>';
                            }
                            else {
                                tbody += '<td>'+imgtag+'</td>';
                            }
                            break;
                        default:
                            if (col.edittype) {
                                var editclass = ' class="' + col.edittype + '-' + col.key + '"';
                                var keyk = (col.edittype == 'ddbox') ? col.key + '-value' : col.key;
                                tbody += '<td><div' + editclass + '>' + m[keyk] + '</div><div' + hide + '>' + m[col.key] + '</div><div' + hide + '>' + m[args.key] + '</div></td>';
                            } else {
                                tbody += '<td>' + m[col.key] + '</td>';
                            }
                            break;
                    }
                });
                if (editable) {
                    tbody += '<td class="edit-operate"><button' + hide + ' type="button" class="btn btn-success" command="save">保存</button>';
                    tbody += '&nbsp;<button' + hide + ' type="button" class="btn btn-default" command="cancel">取消</button></td>';
                }
                tbody += '</tr>';
            });

            if (tbody == '')
                tbody = '<tr><td colspan="' + (cols.length + 1) + '"><div class="alert alert-danger" role="alert">No Records !</div></td></tr>';

            var table = '<table class="table table-stripped table-hover"><thead><tr>' + thead + '</tr></thead><tbody>' + tbody + '</tbody></table>';

            this.element.html(table);
            if (editable && !document.getElementById(args.editpanelid)) {

                var ephtml = '<div id="' + args.editpanelid + '"' + hide + '>';//
                $(editcols).each(function (i, col) {
                    if (col.edittype == 'ddbox') {
                        ephtml += '<select id="editpanel-ddbox-' + col.key + '" class="form-control m-b" style="width:90%;" >';
                        $(args.supportdata[col.key]).each(function (i, item) {
                            ephtml += '<option value="' + item['key'] + '">' + item['value'] + '</option>';
                        });
                        ephtml += '</select>';
                    }
                    if (col.edittype == 'text') {
                        ephtml += '<input id="editpanel-text-' + col.key + '" type="text" class="form-control" style="width:90%;" />';
                    }
                    //if (col.edittype == 'img') {
                    //}
                });

                if (isimg) {
                    ephtml += '<div id="editpanel-img-' + args.id + '-uploader" class="rows" style="font-size:x-small;"><div id="editpanel-img-' + args.id + '-filePicker">选择</div></div>';
                }
                ephtml += '</div>';

                this.element.after(ephtml);

                // event td click

                this.element.click(function (e) {
                    e = e || window.event;
                    var target = e.target || e.srcElement;
                    if (target.nodeName.toString() == "DIV") {
                        target = $(target).parent()[0];
                    }
                    if (target.nodeName.toString() == "TD") {
                        $(target).parent().find('td').each(function (i, td) {
                            var divs = $(td).find('div');
                            if (divs.length == 3) {
                                target = divs[0];
                                thisobj.editevent(target);
                            }
                        });
                    }
                    if (target.nodeName.toString() == "BUTTON") {
                        var command = $(target).attr('command');
                        if (command == 'save') {
                            $('.edit-operate button').hide();
                            thisobj.editsave(target);

                        } else if (command == 'cancel') {
                            $('.edit-operate button').hide();
                            thisobj.editcancel(target);
                        }
                    }
                });
            }

        },

        editevent: function (target) {
            var thisobj = this;
            var args = this.settings;
            var editable = args.editable, editpanelid = 'editpanel-' + args.id;
            var editclass = $(target).attr('class');
            if (editclass.indexOf('ddbox') == 0 || editclass.indexOf('text') == 0) {
                var count = $('#' + editpanelid).find('#editpanel-' + editclass).length;
                if (count == 1) {
                    var val = $(target).next().html();
                    $(target).empty().append($('#editpanel-' + editclass).val(val));
                    var tds = $(target).parent().parent().find('td');
                    $(tds[tds.length - 1]).find('button').show();
                }
            }
            if (editclass.indexOf('img') == 0) {
                
                $imguploadtag = $('#' + editpanelid).find('#editpanel-img-' + args.id + '-uploader');
                var count = $imguploadtag.length, key = editclass.replace('img-', '');
                if (count == 1) {
                    var val = $(target).find('img').attr('src');
                    var imgtag = '<img src="' + val + '" alt="img-edit" style="width:' + args.imgSize[key][0] + 'px;height:' + args.imgSize[key][1] + 'px;"/>';
                    $imguploadtag.prepend(imgtag);
                    $(target).empty().append($imguploadtag);
                    thisobj.upload(args, key, val);
                    var tds = $(target).parent().parent().find('td');
                    $(tds[tds.length - 1]).find('button').show();
                }

            }
        },

        editcancel: function (target) {

            var thisobj = this;
            var args = thisobj.settings;
            var editable = args.editable, editpanelid = 'editpanel-' + args.id;

            var $editpanel = $('#' + editpanelid);
            $(target).parent().parent().find('td').each(function (i, td) {
                var divs = $(td).find('div');
                if (divs.length == 3) {
                    var target1 = divs[0];
                    var editclass = $(target1).attr('class');
                    if (editclass.indexOf('ddbox') == 0 || editclass.indexOf('text') == 0) {
                        var count = $editpanel.find('#editpanel-' + editclass).length;
                        if (count == 0) {
                            var $editctril = $('#editpanel-' + editclass);
                            $editpanel.append($editctril);

                            var val = $(target1).next().html();
                            $editctril.val(val);

                            if (editclass.indexOf('text') == 0) {
                                $(target1).html(val);
                            } else {
                                $(target1).html($editctril.find('option:selected').text());
                            }
                        }
                    }
                } else {
                    var $img = $(td).find('img');
                    if ($img.length == 1 && $img.attr('alt') == 'img-edit') {
                        $editpanel.append('<div id="editpanel-img-' + args.id + '-uploader" class="rows" style="font-size:x-small;"><div id="editpanel-img-' + args.id + '-filePicker">选择</div></div>');
                        var value = $(divs[divs.length - 2]).text();
                        var $target1 = $(divs[0]), colkey = $target1.attr('class').toString().split('-')[1];
                        //console.log($(divs[divs.length - 2]).text());
                        $target1.html('<img src="' + args.imgroot + value + '" alt="" style="width:' + args.imgSize[colkey][0] + 'px;height:' + args.imgSize[colkey][1] + 'px;"/>');
                    }
                }
            });
        },

        editsave: function (target) {
            var thisobj = this;
            var args = thisobj.settings;
            var editable = args.editable, editpanelid = 'editpanel-' + args.id;
            var $editpanel = $('#' + editpanelid);
            var data = {};

            $(target).parent().parent().find('td').each(function (i, td) {
                var divs = $(td).find('div');
                if (divs.length == 3) {
                    var target1 = divs[0];
                    var editclass = $(target1).attr('class');
                    if (editclass.indexOf('ddbox') == 0 || editclass.indexOf('text') == 0) {
                        var count = $editpanel.find('#editpanel-' + editclass).length;
                        if (count == 0) {
                            var $editctril = $('#editpanel-' + editclass), colkey = $(target1).attr('class').toString().split('-')[1];
                            var value = $editctril.val();
                            $(target1).next().html(value);

                            data[args.key] = $(target1).next().next().html();
                            data[colkey] = value;

                            $editpanel.append($editctril);
                            if (editclass.indexOf('text') == 0) {
                                $(target1).html(value);
                            } else {
                                var valuekey = $editctril.find('option:selected').text();
                                data[colkey + '-value'] = valuekey;
                                $(target1).html(valuekey);
                            }
                        }
                    }
                } else {
                    var $img = $(td).find('img');
                    if ($img.length == 1 && $img.attr('alt') == 'img-edit') {
                        var value = $img.attr('src');
                        var target1 = divs[0], colkey = $(target1).attr('class').toString().split('-')[1];
                        var imgtag = '<img src="' + value + '" alt="" style="width:' + args.imgSize[colkey][0] + 'px;height:' + args.imgSize[colkey][1] + 'px;"/>';
                        if (value.indexOf('?t=') > 0)
                            value = value.toString().substr(0, value.indexOf('?t='));
                        data[colkey] = value.replace(args.imgroot, '');
                        $editpanel.append('<div id="editpanel-img-' + args.id + '-uploader" class="rows" style="font-size:x-small;"><div id="editpanel-img-' + args.id + '-filePicker">选择</div></div>');
                        $(target1).html(imgtag);
                    }
                }
            });

            if (args.save) {
                args.save(data, args);
            }

        },

        isIE: function () { //https://gist.github.com/padolsey/527683
            var undef,
                v = 3,
                div = document.createElement("div"),
                all = div.getElementsByTagName("i");

            while (
                div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->",
                all[0]
            ) {
                return v > 4 ? v : undef;
            }
        },

        remove: function () {
            this.element.off("." + pluginName);
            this.element.removeData(pluginName);
        },

        upload: function (args, key, url) {
            var thisobj = this;
            var uploader = WebUploader.create({
                file: { id: 'editpanel-img-'+args.id + "-uploader" }, // file: { id: "uploader-demo" }
                auto: true, // 选完文件后，是否自动上传。                
                server: args.uploadServerUrl, //server: '/UI/UploadImages/', // 文件接收服务端。                
                pick: '#editpanel-img-'+ args.id + '-filePicker', // 内部根据当前运行是创建，可能是input元素，也可能是flash.                
                accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } // 只允许选择图片文件。
            });
            uploader.on('fileQueued', function (file) {
                this.options.formData.FileName = url.replace(args.imgroot, '').replace(/\//g,'\\');
                this.options.formData.SavePath = args.imgSavePath;
            });
            // 文件上传成功，给item添加成功class, 用样式标记上传成功。
            uploader.on('uploadSuccess', function (file) {
                var $img = $('#' + this.options.file.id).find('img');
                $img.attr('src', $img.attr('src') + '?t=' + (new Date()).getMilliseconds());
                $('#' + file.id).addClass('upload-state-done');
            });

        },
    };


    $.fn[pluginName] = function (options) {
        this.each(function () {
            var el = $(this);
            if (el.data(pluginName)) {
                el.data(pluginName).remove();
            }
            el.data(pluginName, new Plugin(this, options));
        });
        return this;
    };

})(jQuery, window, document);